"需要在background.js中运行本文件";
import { createExpressWs } from "albert.gao/node/network2";
import AutoImport from "albert.gao/default/backend-auto-import2";
import { ref, Ref } from "vue";
import type { Server } from "ws";

function getIsProduction(): Ref<boolean> {
  try {
    const electron = require("electron");
    return ref(electron.app.isPackaged);
  } catch (error) {
    return ref(process.env.NODE_ENV === "production");
  }
}

/** 是否为生产模式 */
export const isProd = ref(getIsProduction());

/** Websocket Server */
export const Wss = ref<Server>();

export interface Options {
  production: boolean;
  port: number;
  changePortWhenOccupied?: boolean;
}

/**
 * 服务器入口
 * @param param0
 * @returns
 */
async function startServer({ production = true, port = 8080 }: Options) {
  production
    ? console.log("Server running in production mode")
    : console.log("Server running in development mode");
  isProd.value = production;
  const result = await createExpressWs({
    port,
    portMode: "change-when-occupied",
    setups: [AutoImport],
  });
  Wss.value = result.wss;
  return result;
}

export default startServer;
